import { Button, Flex, Spin, Upload, message } from "antd"
import Cropper, { ReactCropperElement } from "react-cropper";
import "cropperjs/dist/cropper.css";
import { forwardRef, useState } from "react";

const UploadAvatar = forwardRef<ReactCropperElement, { img: string }>((props, ref) => {
    const [img, setImg] = useState(props.img)
    const [loading, setLoading] = useState(false)
    return <div>
        {loading && <Spin></Spin>}
        <Cropper
            ref={ref}
            src={img}
            style={{ width: "100%", height: 400 }}
            aspectRatio={1}
            zoomTo={1}
            autoCropArea={0.8}
            responsive
            dragMode="move"
            viewMode={1}
            preview=".preview_cc_avatar"
            cropBoxMovable={false}
            cropBoxResizable={false}
            minCropBoxHeight={32}
            minCropBoxWidth={32}
            guides={true}></Cropper>
        <Flex align="center" style={{ paddingTop: 8 }} gap={16}>
            <Upload
                showUploadList={false}
                beforeUpload={(file) => {
                    if (file.size > 1024 * 1024 * 20) {
                        message.error("文件太大，请小于20M")
                        return Upload.LIST_IGNORE
                    }
                    if (file.type.startsWith("image")) {
                        return false
                    }
                    else {
                        message.error("文件不是图像类型")
                        return Upload.LIST_IGNORE
                    }
                }}
                onChange={(info) => {
                    const reader = new FileReader();
                    setLoading(true)
                    reader.addEventListener('load', () => { setLoading(false); setImg(reader.result as string) });
                    reader.readAsDataURL(info.file as any);
                }}
            >
                <Button>选择图像</Button>
            </Upload>
            <div className="preview_cc_avatar" style={{ width: 128, height: 128, overflow: "hidden", borderRadius: "50%" }}></div>
            <div className="preview_cc_avatar" style={{ width: 96, height: 96, overflow: "hidden", borderRadius: "50%" }}></div>
            <div className="preview_cc_avatar" style={{ width: 64, height: 64, overflow: "hidden", borderRadius: "50%" }}></div>
        </Flex>
    </div>
})

export default UploadAvatar